package cn.chinaunicom.sdsi.frm.workflow.traffic;

import cn.chinaunicom.sdsi.frm.base.BaseController;
import cn.chinaunicom.sdsi.frm.sys.service.SysStaffService;
//import cn.chinaunicom.sdsi.frm.workflow.users.model.UserMonitor;
//import cn.chinaunicom.sdsi.frm.workflow.users.service.UsersUniversalService;
/*import cn.chinaunicom.sdsi.frm.workflow.users.utils.TextTools;*/
/*import cn.chinaunicom.sdsi.gacx.sys.service.GaAreaLocinfoService;*/
import cn.chinaunicom.sdsi.frm.workflow.traffic.dao.GeneralDao;
import cn.chinaunicom.sdsi.frm.workflow.traffic.dao.dao.mybatis.GeneralTestDao;
import com.alibaba.fastjson.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;


/**
 * Created by adinlead on 17-7-3.
 */
@Controller("configurationController")
@RequestMapping(value = "/configuration")
public class ConfigurationController extends BaseController {

    private final Logger log = Logger.getLogger(this.getClass());

    /**
     * 工作流任务相关的业务逻辑组件
     */
    @Autowired
    private GeneralDao generalDao;
    @Autowired
    private GeneralTestDao generalTestDao;
    /*private UsersUniversalService usersUniversalService;
    private GaAreaLocinfoService gaAreaLocinfoService;*/

    @Autowired
    private SysStaffService sysStaffService;
    /**
     * 测试
     */
    @RequestMapping("/getOneGridHotData")
    @ResponseBody
    public JSONObject getUserMonitorListByType() {

        List<String> list=generalTestDao.test();
        String str = JSON.toJSONString(list);
        String  res0=str.replace("\"[","[").replace("]\"","]");
        JSONObject res=new JSONObject();
        System.out.println("00000000000000000000000000000"+res0);

        res.put("data",res0);
        res.put("status",200);
        return res;
    }

    /**
     * 热力图数据
     */
    @RequestMapping("/getGridHotData")
    @ResponseBody
    public JSONObject getGridHotData(String type ){

        long t1=System.currentTimeMillis();
        List<Map<String, Object>> list=generalDao.getGridHotData(type);
       /* long t4=System.currentTimeMillis();
        System.out.println("======================"+(t4-t1));
        JSONObject temp=new JSONObject();

        JSONArray testArray=new JSONArray();
        for(Map<String, Object> ss : list){
            testArray.add(new String[]{ss.get("lon").toString(),ss.get("lat").toString(),ss.get(type).toString()});
            temp.put(type,testArray);
        }
        System.out.println("============================================");
        System.out.println(temp);
        long t2=System.currentTimeMillis();
        System.out.println("==========-=000000000000000000000000"+(t2-t1));
        */
        JSONObject result=new JSONObject();

        result.put("data",list);
        result.put("status",200);
        return result;
       /* Map<String, Object> hh=list.get(0);
        Integer i=0;
        for(Object key:hh.keySet()){
            if(!key.toString().equals("grid_id")&&!key.toString().equals("lon")&&!key.toString().equals("lat")){
                JSONArray jsonArray=new JSONArray();
                for(Map<String, Object> ss : list){
                    jsonArray.add(new String[]{ss.get("lon").toString(),ss.get("lat").toString(),ss.get(key).toString()});
                    temp.put(i,jsonArray);
                }
                i++;
            }
        }*/


    }

    /**
     * 居住工作数据
     */
    @RequestMapping("/getGridData")
    @ResponseBody
    public JSONObject getGridData(int type) {

        List<Map<String, Object>> list=generalDao.getGridData();

        JSONObject temp=new JSONObject();
        JSONArray jsonArray=new JSONArray();

        for(Map<String, Object> ss : list){

            temp.put("coord",new String[]{ss.get("lon").toString(),ss.get("lat").toString()});
            if(type==1){//居住人事
                temp.put("elevation",Integer.parseInt(ss.get("residents").toString()));
            }else{
                //工作人数
                System.out.println(ss);
                System.out.println(ss.get("workers"));
                temp.put("elevation",Integer.parseInt(ss.get("workers").toString()));
            }

            jsonArray.add(temp);
        }
        JSONObject result=new JSONObject();
        result.put("data",jsonArray);
        result.put("status",200);

        /*试一下=========*/
        /*   lon经度 lat纬度*/
        /*JSONObject tempTest=new JSONObject();
        JSONArray resArray=new JSONArray();

        for(Map<String, Object> ss : list){
            JSONArray testArray=new JSONArray();
            if(type==1){
                //居住人事
                testArray.add(new String[]{ss.get("lon").toString(),ss.get("lat").toString(),ss.get("lon1").toString(),ss.get("lat1").toString(),ss.get("residents").toString()});

            }else{
                //工作人数
                testArray.add(new String[]{ss.get("lon").toString(),ss.get("lat").toString(),ss.get("lon1").toString(),ss.get("lat1").toString(),ss.get("workers").toString()});

            }
            resArray.add(testArray);

        }
        System.out.println("00000000000000000000000000000000000");
        System.out.println(resArray);*/
        /*=====================*/
        return result;

    }
















    /**
     * 获取权限
     */
    @RequestMapping("/getPermission")
    @ResponseBody
    public JSONObject getPermission() {
        Map<String, Object> map = new HashMap<String, Object>();
       // Integer staffId = usersUniversalService.getLoginUser().getStaffId();

       // map = sysStaffService.searchStaffMapById(staffId);
       // return JSONObject.fromObject(JSON.toJSON(map).toString());
    return  null;

    }


    /**
     * 短信日志留存
     */
    @RequestMapping("/template")
    public ModelAndView infocollision() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("frm/workflow/configuration/template");
        mv.addObject("currentId", this.getCurrentSysStaffOrg().getStaffOrgId().toString());
        log.info("短信日志留存！");
        return mv;
    }



    /**
     * URL过滤
     */
    @RequestMapping("/euosar")
    public ModelAndView eunopsysactredPage() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("frm/workflow/configuration/eunopsysactred");
        mv.addObject("currentId", this.getCurrentSysStaffOrg().getStaffOrgId().toString());
        log.info("URL过滤！");
        return mv;
    }

    /**
     * API
     */
    @RequestMapping("/apinfo")
    public ModelAndView apiInfoPage() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("frm/workflow/configuration/api_info");
        mv.addObject("currentId", this.getCurrentSysStaffOrg().getStaffOrgId().toString());
        log.info("URL过滤！");
        return mv;
    }

    /**
     * API
     */
    @RequestMapping("/apiInterfaceQuery")
    public ModelAndView apiInterfaceQuery() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("frm/workflow/configuration/API_interface_query");
        mv.addObject("currentId", this.getCurrentSysStaffOrg().getStaffOrgId().toString());
        log.info("API接口查询！");
        return mv;
    }

    /**
     * 获取单位列表
     *
     * @return
     */
    @RequestMapping("/getCompany")
    @ResponseBody
    public JSONObject getCompany() {
        JSONObject json = new JSONObject();
        json.put("data", generalDao.getCompany());
        json.put("status", 200);
        return json;
    }

    /**
     * 获取公安系统信息
     *
     * @return
     */
    @RequestMapping("/policeInfo")
    @ResponseBody
    public JSONObject policeInfo(int page, int rows, String org_name, Date check_time1, Date check_time2, String is_valid) {
        JSONObject json = generalDao.policeInfo(page, rows, org_name, check_time1, check_time2, is_valid).toJSON();
        return json;
    }

    /**
     * 测试代码
     */
    @RequestMapping("/enclosure")
    public ModelAndView enclosure() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("frm/workflow/configuration/enclosure");
        mv.addObject("currentId", this.getCurrentSysStaffOrg().getStaffOrgId().toString());
        log.info("短信日志留存！");
        return mv;
    }

    /**
     * 短信发送日志
     */
    @RequestMapping("/smsLog")
    public ModelAndView smsLog() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("frm/workflow/configuration/sms_log");
        mv.addObject("currentId", this.getCurrentSysStaffOrg().getStaffOrgId().toString());
        log.info("短信发送日志！");
        return mv;
    }

    /**
     * 告警日志
     */
    @RequestMapping("/alarmLog")
    public ModelAndView alarmLog() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("frm/workflow/configuration/alarm_log");
        mv.addObject("currentId", this.getCurrentSysStaffOrg().getStaffOrgId().toString());
        log.info("短信发送日志！");
        return mv;
    }

    /**
     * 告警日志
     */
    @RequestMapping("/push_ftp_log")
    public ModelAndView pushFTPLog() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("frm/workflow/configuration/push_ftp_log");
        mv.addObject("currentId", this.getCurrentSysStaffOrg().getStaffOrgId().toString());
        log.info("短信发送日志！");
        return mv;
    }

    /**
     * 告警日志
     */
    @RequestMapping("/push_url_log")
    public ModelAndView pushURLLog() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("frm/workflow/configuration/push_url_log");
        mv.addObject("currentId", this.getCurrentSysStaffOrg().getStaffOrgId().toString());
        log.info("短信发送日志！");
        return mv;
    }

    /**
     * 红名单用户
     */
    @RequestMapping("/userread")
    public ModelAndView userreadPage() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("frm/workflow/configuration/user_read");
        mv.addObject("currentId", this.getCurrentSysStaffOrg().getStaffOrgId().toString());
        log.info("转跳到：红名单用户！");
        return mv;
    }

    /**
     * 特殊人员名单
     */
    @RequestMapping("/usermonitor")
    public ModelAndView usermonitorPage() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("frm/workflow/configuration/user_monitor");
        mv.addObject("currentId", this.getCurrentSysStaffOrg().getStaffOrgId().toString());
        log.info("转跳到：特殊人员名单！");
        return mv;
    }

    /**
     * FTP配置页
     */
    @RequestMapping("/ftpconfig")
    public ModelAndView ftpconfigPage() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("frm/workflow/configuration/sys_ftp_config");
        mv.addObject("currentId", this.getCurrentSysStaffOrg().getStaffOrgId().toString());
        log.info("转跳到：FTP设置页");
        return mv;
    }






    /**
     * 黑名单用户
     */
    @RequestMapping("/userblack")
    public ModelAndView userblackPage() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("frm/workflow/configuration/user_black");
        mv.addObject("currentId", this.getCurrentSysStaffOrg().getStaffOrgId().toString());
        log.info("转跳到：黑名单用户！");
        return mv;
    }





    /**
     * @return
     */
    @RequestMapping("/delapi")
    @ResponseBody
    public JSONObject deleteAPIInfo(String api_id) {
        JSONObject json = new JSONObject();
        json.put("status", 200);
        json.put("result", generalDao.deleteAPIInfo(api_id));
        return json;
    }

    /**
     * @return
     */
    @RequestMapping("/getapilist")
    @ResponseBody
    public JSONObject getAPIInfoList2() {
        JSONObject json = new JSONObject();
        json.put("status", 200);
        json.put("result", generalDao.getAPIInfoList(null, null, null, null));
        return json;
    }

    /**
     * @return
     */
    @RequestMapping("/checkAPIInfoList")
    @ResponseBody
    public JSONObject checkAPIInfoList(String apiname, String apiInfo, String letterNeed, String jurisdictionNeed, String buff) {
        buff = "";
        JSONObject json = new JSONObject();
        json.put("status", 200);
        json.put("result", generalDao.checkAPIInfoList(apiname, apiInfo, letterNeed, jurisdictionNeed, buff));
        return json;
    }

    /**
     * 文件下载
     *
     * @param response
     * @return
     * @Description:
     */
    @RequestMapping("/downfile")
    public void downloadFile(String filepath, HttpServletResponse response) {
        if (filepath != null) {
            File file = new File(filepath);
            String filename = filepath.substring(filepath.lastIndexOf("/") + 1, filepath.length());
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + URLEncoder.encode(filename));// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();

                    try {
                        response.setContentType("text/html;charset=UTF-8");
                        response.setCharacterEncoding("UTF-8");
                        response.setStatus(444);
                        response.getWriter().print("<script>parent.layer.msg('访问文件异常！',{icon:7})</script>");
                    } catch (IOException e1) {
                        e.printStackTrace();
                    }
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            } else {

                try {
                    response.setContentType("text/html;charset=UTF-8");
                    response.setCharacterEncoding("UTF-8");
                    response.setStatus(444);
                    response.getWriter().print("<script>parent.layer.msg('此文件不存在！',{icon:7});</script>");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



}